package jp.heartdokyun.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

import jp.heartdokyun.MainGamePanel;
import jp.heartdokyun.R;
import jp.heartdokyun.listener.GoBackListener;
import jp.heartdokyun.listener.TopBackListener;
import jp.heartdokyun.model.Level;
import jp.heartdokyun.util.Utils;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class GameActivity extends Activity {
	// private boolean isTouch;
	private static TextView mTVHeartPercent, mtvTitle;
	private static int mGamePoint;
	private static ImageView mIVHeartPercent, mIVLevelImg;
	private static CountDownTimer mCountDownTimer;
	private int mMaxDurationTime;
	private MainGamePanel mGamePanel;
	private LinearLayout mLLGamePanel;
	private static String mType, mLevel;
	private static Intent itGameSucess;
	private static Context mContext;
	private TextView mTVGameTime;
	private static HashMap<Integer, Integer> soundPoolMap;
	private static SoundPool mSoundPool;
	private static int mPlayedTime;
	private MediaPlayer mMediaPlayer;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.game);
		initSounds();
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		mContext = this;

		mTVHeartPercent = (TextView) findViewById(R.id.tv_game_heart_percent);
		mIVHeartPercent = (ImageView) findViewById(R.id.iv_game_heart_percent);
		mIVLevelImg = (ImageView) findViewById(R.id.iv_game_level_img);

		mTVGameTime = (TextView) findViewById(R.id.tv_game_time);

		// isTouch = false;
		mtvTitle = (TextView) findViewById(R.id.tv_game_title);

		itGameSucess = new Intent(GameActivity.this, GameSuccessActivity.class);
		itGameSucess.putExtra("CHALLENGE_TYPE",
				getIntent().getStringExtra("CHALLENGE_TYPE"));
		itGameSucess.putExtra("CHALLENGE_TYPE_VALUE", getIntent()
				.getStringExtra("CHALLENGE_TYPE_VALUE"));
		itGameSucess.putExtra("LEVEL", getIntent().getStringExtra("LEVEL"));

		mLevel = getIntent().getStringExtra("LEVEL");
		mType = getIntent().getStringExtra("CHALLENGE_TYPE_VALUE");
		String Title = getResources().getString(R.string.game_tilte) + " "
				+ getIntent().getStringExtra("CHALLENGE_TYPE") + " Lv."
				+ mLevel;
		mtvTitle.setText(Title);

		if (mLevel.equals("")) {
			mLevel = "1";
		}
		String imageId = "circle_" + mType + "_lv" + mLevel;
		mIVLevelImg.setImageResource(getResources().getIdentifier(imageId,
				"drawable", "jp.heartdokyun"));
		// mMaxTimes_a = getResources().getInteger(R.integer.game_maxtimetab_a);
		// mMaxTimes_b = getResources().getInteger(R.integer.game_maxtimetab_b);
		// mMaxTimes_c = getResources().getInteger(R.integer.game_maxtimetab_c);
		// mMaxTimes_d = getResources().getInteger(R.integer.game_maxtimetab_d);
		// mMaxTimes_e = getResources().getInteger(R.integer.game_maxtimetab_e);
		// mMaxTimes_f = getResources().getInteger(R.integer.game_maxtimetab_f);
		ImageButton ibBack = (ImageButton) findViewById(R.id.ib_game_back);
		ibBack.setOnClickListener(new GoBackListener(this));

		mLLGamePanel = (LinearLayout) findViewById(R.id.ll_game_panel);

		mMaxDurationTime = Integer
				.parseInt(getString(R.string.game_time_in_seconds)) * 1000;
		mCountDownTimer = new CountDownTimer(mMaxDurationTime, 100) {

			@Override
			public void onTick(long millisUntilFinished) {
				mTVGameTime.setText(String.valueOf(millisUntilFinished / 1000));
//				mTVGameTime.setText(String.valueOf(millisUntilFinished));
				mPlayedTime = (int) (mMaxDurationTime - millisUntilFinished);
				int n = 1;
				int playtime = (int)millisUntilFinished/100;
				
				if ((playtime%30) == 0) {
//					Log.d("playtime",Long.toString(playtime));
					Random random = new Random();
					int randomSound = 14 + random.nextInt(5);
//					Log.d("randomSound",Integer.toString(randomSound));
					playSound(randomSound, 0);
					n++;
				}
			}

			@Override
			public void onFinish() {
				Intent itGame = new Intent(GameActivity.this,
						GameFailActivity.class);
				itGame.putExtra("CHALLENGE_TYPE",
						getIntent().getStringExtra("CHALLENGE_TYPE"));
				itGame.putExtra("CHALLENGE_TYPE_VALUE", getIntent()
						.getStringExtra("CHALLENGE_TYPE_VALUE"));
				itGame.putExtra("LEVEL", mLevel);
				startActivity(itGame);
			}
		};
		mGamePanel = new MainGamePanel(this, mType, mLevel);
		mLLGamePanel.addView(mGamePanel);

		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					Thread.sleep(10);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				playSound(1, -1);
			}
		}).run();

		ImageButton ibo = (ImageButton) findViewById(R.id.ic_o);
		ibo.setOnClickListener(new TopBackListener(this));
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN
				&& event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			return true;
		}
		return false;
	}

	@Override
	public void onBackPressed() {
		mCountDownTimer.cancel();
		super.onBackPressed();
	}

	@Override
	public void onPause() {
		mCountDownTimer.cancel();
		mGamePanel.stopGame();
		// if (mMediaPlayer.isPlaying()) {
		// mMediaPlayer.pause();
		// mMediaPlayer.seekTo(0);
		// }
		if (mMediaPlayer != null)
			mMediaPlayer.release();
		super.onPause();
	}

	@Override
	public void onDestroy() {
		mSoundPool.release();
		if (mMediaPlayer != null)
			mMediaPlayer.release();
		super.onDestroy();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		mLevel = intent.getExtras().getString("LEVEL");
		mType = intent.getExtras().getString("CHALLENGE_TYPE_VALUE");

		if (mLevel.equals("")) {
			mLevel = "1";
		}
		itGameSucess.putExtra("LEVEL", mLevel);
		String Title = getResources().getString(R.string.game_tilte) + " "
				+ getIntent().getStringExtra("CHALLENGE_TYPE") + " Lv."
				+ mLevel;
		mtvTitle.setText(Title);
		String imageId = "circle_" + mType + "_lv" + mLevel;
		mIVLevelImg.setImageResource(getResources().getIdentifier(imageId,
				"drawable", "jp.heartdokyun"));
		setIntent(intent);
	}

	@Override
	public void onResume() {
		// if (MainActivity.isEnableBGM) {
		// mMediaPlayer.start();
		// } else {
		// if (mMediaPlayer.isPlaying()) {
		// mMediaPlayer.pause();
		// mMediaPlayer.seekTo(0);
		// }
		// }

		if (MainActivity.isEnableBGM) {
			mMediaPlayer = MediaPlayer.create(getApplicationContext(),
					R.raw.game_bgm);
			float volume = Utils.getBGMVolume(getApplicationContext());
			mMediaPlayer.setVolume(volume, volume);
			mMediaPlayer.setLooping(true);
			mMediaPlayer.start();
		}
		mGamePoint = 0;
		updateHeartPercent(0);
		mIVHeartPercent.setImageResource(R.drawable.heart_gazi_0);

		mCountDownTimer.start();
		mLLGamePanel.removeView(mGamePanel);
		mGamePanel = null;
		mGamePanel = new MainGamePanel(this, mType, mLevel);
		mLLGamePanel.addView(mGamePanel);
		playSound(1, -1);
		super.onResume();
	}

	public static void updateHeartPercent(int point) {
		// int maxGamePoint = Resources.getSystem().getInteger(
		// R.integer.game_heartc_point);
		int maxGamePoint = 10000;
		mGamePoint += point;
		if (mGamePoint * 100 / maxGamePoint <= 5) {
			mIVHeartPercent.setImageResource(R.drawable.heart_gazi_1);
		} else if (mGamePoint * 100 / maxGamePoint <= 10) {
			mIVHeartPercent.setImageResource(R.drawable.heart_gazi_2);
		} else if (mGamePoint * 100 / maxGamePoint <= 15) {
			mIVHeartPercent.setImageResource(R.drawable.heart_gazi_3);
		} else if (mGamePoint * 100 / maxGamePoint <= 20) {
			mIVHeartPercent.setImageResource(R.drawable.heart_gazi_4);
		} else if (mGamePoint * 100 / maxGamePoint <= 25) {
			mIVHeartPercent.setImageResource(R.drawable.heart_gazi_5);
		} else if (mGamePoint * 100 / maxGamePoint <= 30) {
			mIVHeartPercent.setImageResource(R.drawable.heart_gazi_6);
		} else if (mGamePoint * 100 / maxGamePoint <= 35) {
			mIVHeartPercent.setImageResource(R.drawable.heart_gazi_8);
		} else if (mGamePoint * 100 / maxGamePoint <= 40) {
			mIVHeartPercent.setImageResource(R.drawable.heart_gazi_8);
		} else if (mGamePoint * 100 / maxGamePoint <= 45) {
			mIVHeartPercent.setImageResource(R.drawable.heart_gazi_9);
		} else if (mGamePoint * 100 / maxGamePoint <= 50) {
			mIVHeartPercent.setImageResource(R.drawable.heart_gazi_10);
		} else if (mGamePoint * 100 / maxGamePoint <= 55) {
			mIVHeartPercent.setImageResource(R.drawable.heart_gazi_11);
		} else if (mGamePoint * 100 / maxGamePoint <= 60) {
			mIVHeartPercent.setImageResource(R.drawable.heart_gazi_12);
		} else if (mGamePoint * 100 / maxGamePoint <= 65) {
			mIVHeartPercent.setImageResource(R.drawable.heart_gazi_13);
		} else if (mGamePoint * 100 / maxGamePoint <= 70) {
			mIVHeartPercent.setImageResource(R.drawable.heart_gazi_14);
		} else if (mGamePoint * 100 / maxGamePoint <= 75) {
			mIVHeartPercent.setImageResource(R.drawable.heart_gazi_15);
		} else if (mGamePoint * 100 / maxGamePoint <= 80) {
			mIVHeartPercent.setImageResource(R.drawable.heart_gazi_16);
		} else if (mGamePoint * 100 / maxGamePoint <= 85) {
			mIVHeartPercent.setImageResource(R.drawable.heart_gazi_17);
		} else if (mGamePoint * 100 / maxGamePoint <= 90) {
			mIVHeartPercent.setImageResource(R.drawable.heart_gazi_18);
		} else if (mGamePoint * 100 / maxGamePoint <= 95) {
			mIVHeartPercent.setImageResource(R.drawable.heart_gazi_19);
		} else if (mGamePoint * 100 / maxGamePoint >= 100) {
			mIVHeartPercent.setImageResource(R.drawable.heart_gazi_20);
		}

		if ((mGamePoint * 100 / maxGamePoint <= 30)
				&& (mGamePoint * 100 / maxGamePoint > 5)) {
			playSound(2, 0);
			playSound(3, 0);
			playSound(4, 0);
		} else if ((mGamePoint * 100 / maxGamePoint <= 60)
				&& (mGamePoint * 100 / maxGamePoint > 30)) {
			playSound(5, 0);
			playSound(6, 0);
			playSound(7, 0);
		} else if ((mGamePoint * 100 / maxGamePoint <= 90)
				&& (mGamePoint * 100 / maxGamePoint > 60)) {
			playSound(8, 0);
			playSound(9, 0);
			playSound(10, 0);
		} else if ((mGamePoint * 100 / maxGamePoint <= 99)
				&& (mGamePoint * 100 / maxGamePoint > 90)) {
			playSound(11, 0);
			playSound(12, 0);
		} else if (mGamePoint * 100 / maxGamePoint >= 100) {
			playSound(13, 0);
		}

		if (mGamePoint * 100 / maxGamePoint < 100) {
			mTVHeartPercent.setText(mGamePoint * 100 / maxGamePoint + "%");
		} else {
			mTVHeartPercent.setText("100%");
			saveGame();
			itGameSucess.putExtra("PLAYED_TIME", mPlayedTime);
			mContext.startActivity(itGameSucess);
		}
	}

	static void saveGame() {
		ArrayList<Level> listLevel = Utils.getListLevelFromType(mType);
		for (Level lv : listLevel) {
			if (lv.getLevel().equals(mLevel)) {
				String time = lv.getTime();
				if (!time.equals("")) {
					if (Integer.parseInt(time) > mPlayedTime) {
						lv.setTime(String.valueOf(mPlayedTime));
						lv.setRank(getRank(mLevel, mPlayedTime));
					}
				} else {
					lv.setTime(String.valueOf(mPlayedTime));
					lv.setRank(getRank(mLevel, mPlayedTime));
				}

				Utils.saveDataFile(lv);
			}
		}
		Utils.addLevel(mContext,mType);
	}

	private void initSounds() {
		mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
		soundPoolMap = new HashMap<Integer, Integer>();
		soundPoolMap.put(1,
				mSoundPool.load(getApplicationContext(), R.raw.game_bgm, 1));
		soundPoolMap.put(2, mSoundPool.load(getApplicationContext(),
				R.raw.aaaumaiwa_sexy, 1));
		soundPoolMap.put(3,
				mSoundPool.load(getApplicationContext(), R.raw.mmm_sexy, 1));
		soundPoolMap.put(4,
				mSoundPool.load(getApplicationContext(), R.raw.an_sexy, 1));
		soundPoolMap
				.put(5, mSoundPool.load(getApplicationContext(),
						R.raw.aaaumai_sexy, 1));
		soundPoolMap.put(6,
				mSoundPool.load(getApplicationContext(), R.raw.iyaaan_sexy, 1));
		soundPoolMap.put(7,
				mSoundPool.load(getApplicationContext(), R.raw.mmm_sexy, 1));
		soundPoolMap.put(8,
				mSoundPool.load(getApplicationContext(), R.raw.aaan_sexy, 1));
		soundPoolMap.put(9,
				mSoundPool.load(getApplicationContext(), R.raw.toiki, 1));
		soundPoolMap.put(10,
				mSoundPool.load(getApplicationContext(), R.raw.iiwaaa_sexy, 1));
		soundPoolMap.put(11, mSoundPool.load(getApplicationContext(),
				R.raw.aaanicchau_sexy, 1));
		soundPoolMap.put(12, mSoundPool.load(getApplicationContext(),
				R.raw.ixtsuixtsuikuuu, 1));
		soundPoolMap.put(13,
				mSoundPool.load(getApplicationContext(), R.raw.ikuuu_sexy, 1));
		
		soundPoolMap.put(14,
				mSoundPool.load(getApplicationContext(), R.raw.ganbareeee, 1));
		soundPoolMap.put(15,
				mSoundPool.load(getApplicationContext(), R.raw.hayakuuuu, 1));
		soundPoolMap.put(16,
				mSoundPool.load(getApplicationContext(), R.raw.isogeisoge, 1));
		soundPoolMap.put(17,
				mSoundPool.load(getApplicationContext(), R.raw.jouzu, 1));
		soundPoolMap.put(18,
				mSoundPool.load(getApplicationContext(), R.raw.mottoooo, 1));
//		soundPoolMap.put(19,
//				mSoundPool.load(getApplicationContext(), R.raw.osoiii, 1));
//		soundPoolMap.put(20,
//				mSoundPool.load(getApplicationContext(), R.raw.ossoooi, 1));		

	}

	private static void playSound(int sound, int loop) {
		float volume = Utils.getVoiceVolume(mContext);
		mSoundPool.play(soundPoolMap.get(sound), volume, volume, 1, loop, 1f);
	}

	private static String getRank(String level, int playdTime) {
		String rank = "";
		
		if (level.equals("1")) {
			if (playdTime < 20000) {
				rank = "A";
			} else if (playdTime < 25000) {
				rank = "B";
			} else if (playdTime < 30000) {
				rank = "C";
			}

		} else if (level.equals("2")) {
			if (playdTime < 21000) {
				rank = "A";
			} else if (playdTime < 26000) {
				rank = "B";
			} else if (playdTime < 30000) {
				rank = "C";
			}
		} else if (level.equals("3")) {
			if (playdTime < 22000) {
				rank = "A";
			} else if (playdTime < 27000) {
				rank = "B";
			} else if (playdTime < 30000) {
				rank = "C";
			}
		} else if (level.equals("4")) {
			if (playdTime < 23000) {
				rank = "A";
			} else if (playdTime < 28000) {
				rank = "B";
			} else if (playdTime < 30000) {
				rank = "C";
			}
		} else if (level.equals("5")) {
			if (playdTime < 25000) {
				rank = "A";
			} else if (playdTime < 28000) {
				rank = "B";
			} else if (playdTime < 30000) {
				rank = "C";
			}
		}
		return rank;
	}

}